package com.derekandbritt.booST;

import java.text.SimpleDateFormat;

import org.opensocial.models.Person;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.derekandbritt.booST.data.Challenge;
import com.derekandbritt.booST.data.Challenge.Status;
import com.derekandbritt.booST.exceptions.ConnectionException;
import com.derekandbritt.booST.exceptions.DataFormatException;
import com.derekandbritt.booST.exceptions.GenericException;

public class ChallengeHistory extends booSTActivity {

	public final static String MESSAGE_KEY = "com.derekandbritt.booST.messageFilter";
	public final static String STATUS_KEY = "com.derekandbritt.booST.status";
	
	public final static int STATUS_ALL = 1;
	public final static int STATUS_ACTIVE = 2;
	public final static int STATUS_COMPLETED = 3;
	
	private final static int REFRESH_OPTION = 4;
	private final static int FILTER_OPTION = 5;
	
	private int currentFilter = STATUS_ACTIVE;
	
	public boolean onCreateOptionsMenu(Menu menu) {

	    menu.add(0, REFRESH_OPTION, 0, "Refresh");
  
	    SubMenu statusMenu = menu.addSubMenu(0, FILTER_OPTION, 0, "Status Filter");
	    statusMenu.add(0, STATUS_ALL, 0, "All").setChecked(currentFilter == STATUS_ALL);
	    statusMenu.add(0, STATUS_ACTIVE, 0, "Active").setChecked(currentFilter == STATUS_ACTIVE);
	    statusMenu.add(0, STATUS_COMPLETED, 0, "Completed").setChecked(currentFilter == STATUS_COMPLETED);
	    statusMenu.setGroupCheckable(0, true, true);
    
	    return true;
	}

    public boolean onOptionsItemSelected(MenuItem item) {
        try {
            switch (item.getItemId()) {
                case STATUS_ALL:
                	currentFilter = STATUS_ALL;
                	item.setChecked(true);
                    displayTable();
                	Toast.makeText(this, "all", Toast.LENGTH_SHORT).show();
                    return true;
                case STATUS_ACTIVE:
                	currentFilter = STATUS_ACTIVE;
                	item.setChecked(true);
                	displayTable();
                	Toast.makeText(this, "active", Toast.LENGTH_SHORT).show();
                    return true;
                case STATUS_COMPLETED:
                	currentFilter = STATUS_COMPLETED;
                	item.setChecked(true);
                	displayTable();
                	Toast.makeText(this, "completed", Toast.LENGTH_SHORT).show();
                    return true;
                case REFRESH_OPTION:
                    booSTEndpoint.refreshUser();
                    return true;
            }
        } catch (GenericException e) {
            handleError(e);
        }
        return false;
    }
	
	public void handleResume() throws ConnectionException, DataFormatException {
	    this.setContentView(R.layout.messages);
	    displayTable();
	}
    
	public void displayContent() throws ConnectionException, DataFormatException {
		this.setContentView(R.layout.messages);
		//setup the filter to work based on contents of the intent
		currentFilter = this.getIntent().getIntExtra(STATUS_KEY, STATUS_ACTIVE);
		displayTable();
	}
	
	private void displayTable() throws ConnectionException, DataFormatException {
		
		Challenge[] challenges = null;
		if(currentFilter == STATUS_ALL) 
			challenges = booSTEndpoint.getChallenges(30);
		else if(currentFilter == STATUS_ACTIVE)
		    challenges = booSTEndpoint.getActiveChallenges();
		else if(currentFilter == STATUS_COMPLETED)
            challenges = booSTEndpoint.getCompletedChallenges(30);
		
		TableLayout table = (TableLayout)findViewById(R.id.Messages_ChallengesTable);
		table.removeAllViews();
        for(Challenge challenge : challenges) {
        	table.addView(generateTableRow(challenge));
        }
	}

	private TableRow generateTableRow(final Challenge challenge) throws ConnectionException, DataFormatException {
    	TableRow row = new TableRow(this);
    	row.setPadding(0, 4, 0, 0);
    	row.setFocusable(true);
    	row.setBackgroundResource(R.color.messages);
    	
    	String userId = booSTEndpoint.getUser().userID;
    	
    	String friendId;
    	if(challenge.getSender().equals(userId))
    		friendId = challenge.getReceiver();
    	else
    		friendId = challenge.getSender();
    	
    	Person friend = osEndpoint.fetchPerson(friendId);
    	
    	// friends name
    	TextView name = new TextView(this);
    	name.setMinWidth(90);
    	name.setMaxWidth(90);
    	name.setMaxLines(1);
    	name.setEllipsize(TextUtils.TruncateAt.END);
    	name.setText(friend.getDisplayName());

    	// challenge type
    	TextView type = new TextView(this);
    	type.setMaxLines(1);
    	type.setMinWidth(85);
    	type.setText(challenge.getType().toString());
    	
    	// date issued
    	SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
    	
    	TextView date = new TextView(this);
    	date.setMaxLines(1);
    	date.setMinWidth(65);
    	date.setText(formatter.format(challenge.getTimeIssued()));
    	
    	// challenge status
    	TextView status = new TextView(this);
    	status.setMaxLines(1);
    	status.setText(getStatusText(challenge));
    	
    	row.addView(name);
    	row.addView(type);
    	row.addView(date);
    	row.addView(status);
    	
    	row.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				Intent intent = new Intent();
				intent.setClassName("com.derekandbritt.booST", "com.derekandbritt.booST.ViewChallenge");
				intent.putExtra(ViewChallenge.CHALLENGE_KEY, challenge.getId());
				view.getContext().startActivity(intent);
			} });
    	
    	return row;
	}
	
	private String getStatusText(final Challenge challenge) throws DataFormatException, ConnectionException {
				
		if(Status.PENDING == challenge.getStatus()) {
			if(challenge.getSender().equals(osEndpoint.getPersonId()))
				return "PENDING";
			else
				return "RECEIVED";
		}
		
		return challenge.getStatus().toString();
	}
	
}
